package com.example.servlet;

import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    public LoginServlet() {
        super();
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        String username = request.getParameter("username");
        String password = request.getParameter("password");

        String role = null;

        try {
            Context initContext = new InitialContext();
            Context envContext = (Context) initContext.lookup("java:/comp/env");
            DataSource ds = (DataSource) envContext.lookup("jdbc/company");

            try (Connection conn = ds.getConnection();
                 PreparedStatement ps = conn.prepareStatement(
                         "SELECT role FROM user WHERE username = ? AND password = ?")) {

                ps.setString(1, username);
                ps.setString(2, password);

                ResultSet rs = ps.executeQuery();
                if (rs.next()) {
                    role = rs.getString("role"); // 取出用户角色
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (role != null) {
            // 保存登录状态
            HttpSession session = request.getSession();
            ((HttpSession) session).setAttribute("username", username);
            session.setAttribute("role", role);

            // 根据角色跳转
            if ("admin".equals(role)) {
                response.sendRedirect("index.jsp");
            } else if ("employee".equals(role)) {
                response.sendRedirect("employeeshow.jsp");
            } else {
                // 未知角色，返回登录页面
                request.setAttribute("error", "非法用户角色");
                request.getRequestDispatcher("login.jsp").forward(request, response);
            }
        } else {
            // 登录失败
            request.setAttribute("error", "用户名或密码错误");
            request.getRequestDispatcher("login.jsp").forward(request, response);
        }
    }
}